package com.cloudream.controller;

import com.cloudream.entity.User;
import com.cloudream.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {
    private static Logger logger = LoggerFactory.getLogger(IndexController.class);


    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/json")
    public List<String> json() {
        List<String> list = new ArrayList<String>();

        for (int i = 0; i < 10; i++) {
            list.add("xxxxxx" + i);
        }
        return list;
    }

    @RequestMapping(value = "/test")
    public String test() {
        return "test";
    }

    @ResponseBody
    @RequestMapping(value = "/json3")
    public String json3() throws UnsupportedEncodingException {
        String json = "亲请问如图";
//		json = java.net.URLEncoder.encode(json, "UTF-8");
        char[] rtn = json.toCharArray();
        for (int i = 0; i < json.length(); i++) {
            int tmp = json.codePointAt(i);
            tmp += 3;
            rtn[i] = Character.toChars(tmp)[0];
        }
        json = new String(rtn);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/json2")
    public String json2() {
        String json = "[";
        for (int i = 0; i < 10; i++) {
            json += "{";
            json += "\"id\":" + i;
            json += "}";
            if (i != 9) json += ",";
        }
        json += "]";
        return json;
    }

    @ResponseBody
    @RequestMapping("/save")
    public User saveUser() {
        logger.warn("访问--------------------" + IndexController.class.getResource("/"));
        User user = new User();
        user.setUsername("mengxy");
        user.setPassword("mengxy");
        this.userService.saveUser(user);
        return user;
    }

    @ResponseBody
    @RequestMapping("/findbyid/{id}")
    public User findById(@PathVariable long id) {
        return this.userService.findUserById(id);
    }

    @ResponseBody
    @RequestMapping("/findbyusername/{username}")
    public List<User> findByUsername(@PathVariable String username) {
        return this.userService.findUserByUsername(username);
    }
}
